<template>
  <div>
    <el-card style="width:98%;margin:30px auto;">
      <div clas="title" style="font-weight:bold;font-size:17px">报名管理</div>

      <div style="display: flex;justify-content: space-between">
        <div style="margin: 20px 2px">
          <!--          <el-button type="primary" icon="el-icon-plus" circle @click="open" title="添加"></el-button>-->

          <el-button type="danger" @click="deleteBatch" icon="el-icon-delete" title="批量删除" slot="reference"
                     style="margin-left: 10px"></el-button>
        </div>
        <div style="margin: 20px 5px">
          <!--          <el-input v-model="name" style="width: 200px" placeholder="请输入考试名称"
                              suffix-icon="el-icon-search"></el-input>
                    <el-button class="ml-5" type="primary"  style="margin-left: 10px" @click="load">搜索</el-button>
                    <el-button type="warning" @click="reset">重置</el-button>-->
        </div>


      </div>
      <el-table :data="tableData" border stripe :header-cell-class-name="headerBg"
                @selection-change="handleSelectionChange" size="medium"
      >

        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <!--        <el-table-column prop="id" label="ID" width="200">
                </el-table-column>-->
        <el-table-column prop="userId" label="报名人">
          <template slot-scope="scope">
            <span
              v-if="users && users.length">{{
                users.find(v => v.id == scope.row.userId) ? users.find(v => v.id == scope.row.userId).nickname : ''
              }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="examId" label="考试名称">
          <template slot-scope="scope">
            <span
              v-if="exam && exam.length">{{
                exam.find(v => v.id == scope.row.examId) ? exam.find(v => v.id == scope.row.examId).name : ''
              }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="time" :formatter="dateFormat1" label="报名时间">
        </el-table-column>


        <el-table-column prop="state" label="考试状态">
        </el-table-column>
        <el-table-column label="审核" width="240">
          <template slot-scope="scope">
            <el-button type="success" @click="changeChk(scope.row,'审核通过')" >审核通过
            </el-button>
            <el-button type="success" @click="changeChk(scope.row,'审核不通过')" >审核不通过
            </el-button>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <!--            <el-button type="primary" @click="edit(scope.row)" icon="el-icon-edit" circle></el-button>-->

            <!--删除-->
            <el-button @click="delete1(scope.row.id)"
                       slot="reference" type="danger" icon="el-icon-delete" circle
                       style="margin-left: 10px"></el-button>

          </template>
        </el-table-column>
      </el-table>
      <div style="padding: 10px 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      title="新增考试"
      :visible.sync="dialogVisible"
      width="30%"
      :destroy-on-close="true"
    >
      <el-form :model="form" label-width="120px" size="medium" ref="form" class="demo-ruleForm">
        <el-form-item label="考试名称" prop="userId">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>


        <!--        <el-form-item label="课程" prop="courseId">
                  <el-select v-model="form.courseId" placeholder="请选择课程">
                    <el-option v-for="item in courses" :label="item.name" :value="item.id" :key="item.id"></el-option>

                  </el-select>
                </el-form-item>-->
        <!--        <el-form-item label="考试状态" prop="state">-->
        <!--          <el-input v-model="form.state" autocomplete="off"></el-input>-->
        <!--        </el-form-item>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>

    </el-dialog>


  </div>
</template>

<script>
import request from '../../utils/request'

export default {
  name: "Dict",
  data() {
    return {
      exam: [],
      users: [],
      /* rules: {
         name: [
           {required: true, message: '请输入考试名称', trigger: 'blur'}
           // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
         ],
         classroom: [
           {required: true, message: '请输入考试教室', trigger: 'blur'},
           // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
         ],

         time: [
           {required: true, message: '请选择考试时间', trigger: 'blur'}
           // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
         ],
         teacher: [
           {required: true, message: '请输入监考老师', trigger: 'blur'}
           // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
         ], state: [
           {required: true, message: '请选择考试状态', trigger: 'blur'}
           // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
         ],
         courseName: [
           {required: true, message: '请选择课程', trigger: 'blur'}
         ],
         startTime: [
           {required: true, message: '请选择开始时间', trigger: 'blur'}
         ],
         endTime: [
           {required: true, message: '请选择结束时间', trigger: 'blur'}
         ]
       },*/
      roles: [],
      headerBg: 'headerBg',
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 5,
      name: "",
      dialogVisible: false,
      form: {},
      //批量删除
      multipleSelection: [],
      courses: []
    }
  },
  created() {
    //请求数据
    this.load()
    this.request.get("/course/findAll").then(res => {
      this.courses = res.data
    })


  },
  methods: {

    changeChk(row, state) {
      this.form = JSON.parse(JSON.stringify(row))
      this.form.state = state
      this.save()
    },


    dateFormat1(row, column, cellValue, index) {
      const daterc = row[column.property]
      if (daterc != null) {
        var date = new Date(daterc);
        var year = date.getFullYear();
        /* 在日期格式中，月份是从0开始，11结束，因此要加0
         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
         * */
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // 拼接
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
      }
    },


    dateFormat(row) {

      const daterc = row
      if (daterc != null) {
        var date = new Date(daterc);
        var year = date.getFullYear();
        /* 在日期格式中，月份是从0开始，11结束，因此要加0
         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
         * */
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // 拼接
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
      }
    },

    //消除校验
    resetForm() {
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      })

      this.dialogVisible = false

    },
    deleteBatch() {
      let ids = this.multipleSelection.map(v => v.id)  //将对象数变为纯id数组
      this.$confirm('确定批量删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'msgbox',
        type: 'warning'
      }).then(() => {
        request.post("/sign/delBathSign/bath", ids).then(res => {
          if (ids.length === 0) {
            this.$message({
              type: 'warning',
              message: '请选择数据!'
            });
            return
          }
          if (res) {
            this.$message({
              type: 'success',
              message: '批量删除成功!'
            });
            this.load()
          } else {
            this.$message({
              type: 'error',
              message: '批量删除失败!'
            });
          }

        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //批量删除
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    //删除
    delete1(id) {
      this.$confirm('确定删除此icon, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'msgbox',
        type: 'warning'
      }).then(() => {
        request.delete("/sign/del/" + id).then(res => {
          console.log(res)
          if (res) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.load()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }

        })

      }).catch(() => {
        this.$message({
          type: 'success',
          message: '已取消删除'
        });
      });
    },

    //更新
    edit(row) {
      this.form = row
      this.dialogVisible = true
    },

    //新增
    save() {
      // this.$refs['form'].validate((valid) => {
      // if (valid) {  // 表单校验合法

      request.post("/sign/save", this.form).then(res => {

        if (res) {
          this.$message({
            type: "success",
            message: "保存成功"

          })
          this.dialogVisible = false
          this.load()
        } else {
          this.$message({
            type: "error",
            message: "保存失败"
          })
        }
      })
      /*        }
            })*/
    },
    //新增弹窗
    open() {
      this.dialogVisible = true
      this.form = {}
    },
    //重置
    reset() {
      this.name = "",
        this.load()
    },

    //分页
    load() {
      request.get("/sign/findSignPage", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,

        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
      this.request.get('/exam/selectExam').then(res => {
        console.log(res)
        this.exam = res.data
      })
      this.request.get('/user/selectUser').then(res => {
        this.users = res.data
      })

    },
    handleSizeChange(val) {
      this.pageSize = val
      this.load()

    },
    handleCurrentChange(val) {
      this.pageNum = val

      this.load()
    }
  }
}
</script>

<style>
.headerBg {
  background: #eee !important;
}
</style>

<style >

@media (max-width: 720px) {
  .msgbox{
    width: 327px !important;
  }
}

</style>
